#!/bin/bash

# 颜色定义
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
BLUE="\033[0;34m"
NC="\033[0m"

echo -e "\n"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN}         ↓↓ 环境配置向导 ↓↓          ${NC}"
echo -e "${BLUE}====================================${NC}"
echo -e "${YELLOW}  ...请按提示输入完成环境配置...      ${NC}"
echo -e "${BLUE}====================================${NC}"
echo ""

# 定义环境变量文件路径
ENV_FILE=".env"
EXAMPLE_ENV_FILE=".example.env"

# 检查示例文件是否存在
if [ ! -f "$EXAMPLE_ENV_FILE" ]; then
    echo -e "${YELLOW}错误: $EXAMPLE_ENV_FILE 文件不存在!${NC}"
    exit 1
fi

# 尝试使用uname检测架构
if command -v uname &> /dev/null; then
    arch=$(uname -m)
    if [[ "$arch" == "arm64" || "$arch" == "aarch64" ]]; then
        platform_type="arm64"
    elif [[ "$arch" == "x86_64" ]]; then
        platform_type="amd64"
    fi
fi

# 架构获取失败让用户输入
if [ -z "$platform_type" ]; then
    echo -e "${YELLOW}无法自动检测平台类型${NC}"
    # 让用户输入平台类型，并验证
    valid_platform=false
    while [ "$valid_platform" != "true" ]; do
        read -r -p "请输入主机平台(arm64/amd64): " platform_type
        # 检查是否为空
        if [ -z "$platform_type" ]; then
            echo -e "${YELLOW}错误: 主机平台是必填项!${NC}"
            continue
        fi
        # 检查是否为有效值
        if [[ "$platform_type" == "arm64" || "$platform_type" == "amd64" ]]; then
            valid_platform=true
        else
            echo -e "${YELLOW}错误: 平台类型必须是arm64或amd64!${NC}"
        fi
    done
else
    echo -e "${GREEN}检测到平台类型: ${YELLOW}$platform_type${NC}"
fi

# 询问MySQL密码
echo -e "${GREEN}\nMySQL密码(必填)${NC}"
read -r -p "请输入: " mysql_password
while [ -z "$mysql_password" ]; do
    echo -e "${YELLOW}错误: MySQL密码是必填项!${NC}"
    read -r -p "请输入: " mysql_password
done

# 询问Redis密码
echo -e "${GREEN}\nRedis密码(必填)${NC}"
read -r -p "请输入: " redis_password
while [ -z "$redis_password" ]; do
    echo -e "${YELLOW}错误: Redis密码是必填项!${NC}"
    read -r -p "请输入: " redis_password
done

# 询问Postgres密码
echo -e "${GREEN}\nPostgres密码(必填)${NC}"
read -r -p "请输入: " postgres_password
while [ -z "$postgres_password" ]; do
    echo -e "${YELLOW}错误: PostgreSQL密码是必填项!${NC}"
    read -r -p "请输入: " postgres_password
done

# 创建新的.env文件
# shellcheck disable=SC2188
> "$ENV_FILE"

# 读取示例文件并替换
while IFS= read -r line || [ -n "$line" ]; do
    if [[ $line =~ ^PLATFORM_TYPE= ]]; then
        echo "PLATFORM_TYPE=$platform_type" >> "$ENV_FILE"
    elif [[ $line =~ ^MYSQL_PASSWORD= ]]; then
        echo "MYSQL_PASSWORD=$mysql_password" >> "$ENV_FILE"
    elif [[ $line =~ ^REDIS_PASSWORD= ]]; then
        echo "REDIS_PASSWORD=$redis_password" >> "$ENV_FILE"
    elif [[ $line =~ ^POSTGRES_PASSWORD= ]]; then
        echo "POSTGRES_PASSWORD=$postgres_password" >> "$ENV_FILE"
    else
        echo "$line" >> "$ENV_FILE"
    fi
done < "$EXAMPLE_ENV_FILE"

# ======================== 分割线 ======================== #

# 询问网站域名
echo -e "\n${GREEN}请输入网站域名(非必填)${NC}"
read -r -p "请输入域名(例如: www.example.com): " domain
if [ -z "$domain" ]; then
    domain="www.example.localhost"
fi

# 询问后台入口
admin="admin"
#echo -e "\n${GREEN}请输入后台入口(默认: admin)${NC}"
#read -r -p "请输入名称(例如: admin): " admin
#if [ -z "$admin" ]; then
#    admin="admin"
#fi

# 定义模板和目标文件路径
TPL_FILE="config/nginx/vhosts.tpl"
CONF_DIR="config/nginx/conf.d"
TARGET_CONF="config/nginx/conf.d/domain.vhosts.conf"

# 检查模板文件是否存在
if [ ! -f "$TPL_FILE" ]; then
    echo -e "${YELLOW}错误: $TPL_FILE 模板文件不存在!${NC}"
    exit 1
fi

# 确保目标目录存在
if [ ! -d "$CONF_DIR" ]; then
    mkdir -p "$CONF_DIR"
fi

# 替换模板内容
template_content=$(cat "$TPL_FILE")
# shellcheck disable=SC2001
template_content=$(echo "$template_content" | sed "s/www.example.localhost/$domain/g")
# shellcheck disable=SC2001
template_content=$(echo "$template_content" | sed "s|location /admin|location /$admin|g")
echo "$template_content" > "$TARGET_CONF"

# 写入状态输出
# shellcheck disable=SC2320
# shellcheck disable=SC2181
if [ $? -eq 0 ]; then
    echo -e "\n"
    echo -e "${GREEN}Docker配置文件创建成功: .env       ${NC}"
    echo -e "${GREEN}Nginx 配置文件创建成功: $TARGET_CONF${NC}"
else
    echo -e "${YELLOW}\n配置文件创建失败: 请重新尝试!${NC}"
    exit 1
fi

# ======================== 分割线 ======================== #

# 处理server目录下的.env文件
echo -e "\n${GREEN}正在配置server/.env文件...${NC}"

# 定义server目录下的环境变量文件路径
SERVER_DIR="../server"
SERVER_ENV_FILE="$SERVER_DIR/.env"
SERVER_EXAMPLE_ENV_FILE="$SERVER_DIR/.example.env"

# 检查server目录下的示例文件是否存在
if [ ! -f "$SERVER_EXAMPLE_ENV_FILE" ]; then
    echo -e "${YELLOW}警告: $SERVER_EXAMPLE_ENV_FILE 文件不存在!${NC}"
else
    # 创建新的server/.env文件
    # shellcheck disable=SC2188
    > "$SERVER_ENV_FILE"

    # 读取示例文件并替换密码
    while IFS= read -r line || [ -n "$line" ]; do
        if [[ $line =~ ^MYSQL_PASSWORD= ]]; then
            echo "MYSQL_PASSWORD=$mysql_password" >> "$SERVER_ENV_FILE"
        elif [[ $line =~ ^PGSQL_PASSWORD= ]]; then
            echo "PGSQL_PASSWORD=$postgres_password" >> "$SERVER_ENV_FILE"
        elif [[ $line =~ ^REDIS_PASSWORD= ]]; then
            echo "REDIS_PASSWORD=$redis_password" >> "$SERVER_ENV_FILE"
        else
            echo "$line" >> "$SERVER_ENV_FILE"
        fi
    done < "$SERVER_EXAMPLE_ENV_FILE"
    
    # 检查server/.env文件是否创建成功
    write_status=$?
    if [ $write_status -eq 0 ]; then
        echo -e "${GREEN}Server环境配置文件创建成功: $SERVER_ENV_FILE${NC}"
    else
        echo -e "${YELLOW}Server环境配置文件创建失败: 请检查权限或路径!${NC}"
    fi
fi

echo -e "\n"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN}           【配置完成】              ${NC}"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN} 1、.env 配置初始成功!               ${NC}"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN} 2、Nginx 配置初始成功!              ${NC}"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN} 3、Server 配置初始成功!              ${NC}"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN} PS: 现在您可以启动容器了 ~           ${NC}"
echo -e "${BLUE}====================================${NC}"
echo -e "${GREEN} 启动命令: docker-compose -p mdd up -d ${NC}"
echo -e "${BLUE}====================================\n${NC}"
